package com.cashbox.consola;

import com.cashbox.dao.conexiones.ConexionFactory;
import com.cashbox.lanzador.CashBox;
import com.cashbox.logger.CashBoxLogger;
import java.util.List;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author luramirez
 */
public class Consola {

    private String argsString;
    private String param;
    private int coma;
    private EntityManager em;
    private Scanner sc;

    public Consola() {
        em = ConexionFactory.getInstance().getEntitiManager();
    }

    public void getConsoleMode() {
        mjsIniciales();
        while (true) {
            System.out.print(">");
            sc = new Scanner(System.in);
            argsString = sc.nextLine();
            switch (argsString) {
                case "close":
                    new CashBoxLogger(CashBox.class.getSimpleName()).grabarLogINFO("Sesión Finalizada.");
                    return;
                default:
                    modoLectura();
            }
        }
    }

    public void mjsIniciales() {
        System.out.println("CashBox: Sistema de Punto de Ventas");
        System.out.println("Modo Consola");
    }

    public void modoLectura() {
        param = "";
        if (argsString.contains(",")) {
            coma = 0;
            for (char v : argsString.toCharArray()) {
                coma++;
                if (v == ',') {
                    param = argsString.substring(coma, argsString.length());
                    argsString = argsString.substring(0, coma - 1);
                    break;
                }
            }
        }

        try {
            Query qAll = em.createNamedQuery(argsString);
            if (!param.equals("")) {
                qAll.setParameter("id", Long.parseLong(param));
            }
            List lst = qAll.getResultList();
            new CashBoxLogger(CashBox.class.getSimpleName()).grabarLogINFO(
                              "Datos de Consulta -> "+argsString + " "+param+":");
            for (Object object : lst) {
                System.out.println("    -->" + object.toString());
            }
        } catch (Exception ex) {
            new CashBoxLogger(CashBox.class.getSimpleName()).grabarLogINFO(
                              "Comando no Valido la Clase o el Método no Fueron Encontrados. ("+argsString + " "+param+")");
            
        }
    }
}
